package com.qianchang.microfinance.view.credit.data;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import java.util.Timer;
import java.util.TimerTask;

import com.android.moblie.zmxy.antgroup.creditsdk.app.CreditApp;
import com.android.moblie.zmxy.antgroup.creditsdk.app.ICreditListener;
import com.dm.library.http.DMOKHttpUtils;
import com.dm.library.http.HttpParams;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.DMLog;
import com.dm.library.utils.ToastUtil;
import com.dm.library.widgets.element.DButton;
import com.dm.library.widgets.element.DTextView;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.bean.CreditParamBean;
import com.qianchang.microfinance.bean.FindUserBasicInfoBean;
import com.qianchang.microfinance.bean.LoanType;
import com.qianchang.microfinance.bean.TongDunBean;
import com.qianchang.microfinance.bean.UserLoginInfo;
import com.qianchang.microfinance.global.ConstantAppInfo;
import com.qianchang.microfinance.global.DMApplication;
import com.qianchang.microfinance.utils.DMConstant;
import com.qianchang.microfinance.view.base.BaseActivity;
import com.qianchang.microfinance.view.hsdialog.CommunicationServiceDialog;
import com.qianchang.microfinance.view.register.AgreementActivity;

import java.util.HashMap;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.qianchang.microfinance.global.ConstantAppInfo.DEFAULT_TIME;

/**
 * Created by SSC on 2017/12/27.
 *
 *  开始芝麻授权开关按钮页面
 *
 */

public class GoSesameAuthorizedActivity extends BaseActivity{

    @BindView(R.id.bt_next_id)
    DButton button;

    private FindUserBasicInfoBean basicInfoBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gosesameauthorized_layout);
        ButterKnife.bind(this);

        initView();
        initData();

    }

    @Override
    protected void onResume() {
        super.onResume();
        updateStatus();
    }


    private boolean isConfirml = false;

    @Override
    protected void initView() {
        super.initView();
        String title = getString(R.string.zhima_xiyong);
        setTitle(title);

        Bundle bundle = getBundle();
        if(bundle != null){
            isConfirml = bundle.getBoolean("isConfirml",false);
        }

    }

    @Override
    protected void initData() {
        super.initData();

    }


    /**
     * 获取资料认证状态
     */
    private void updateStatus() {
        show();
        HttpParams params = new HttpParams();
        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.FIND_USER_BASIC_INFO, params, new RequestCallBack<FindUserBasicInfoBean>() {
            @Override
            public void onSuccess(JsonResult<FindUserBasicInfoBean> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    basicInfoBean = response.getObject();
                } else {
                    ToastUtil.getInstant().show(getApplicationContext(), response.getDescription());
                }
            }


            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(getApplicationContext(), msg);
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }



    private void refreshView() {

    }



    public static final int BASIC_INFO = 100;

    @OnClick({R.id.bt_next_id})
    public void onViewClicked(View view){
        switch (view.getId()) {
            case R.id.bt_next_id:

                if(basicInfoBean != null){
                    int isTongDunAuth = basicInfoBean.getIsTongDunAuth();
                    int isSesameAuth = basicInfoBean.getIsSesameAuth();

                    if(isTongDunAuth != 0){                             //是否是同盾认证，0已经认证，1未认证
                        //芝麻授权之前先进行同盾认证认证通过了走芝麻授权
                        withTheShieldCertification();
                        return;
                    }

                    if(isSesameAuth != 0){                             //芝麻验证通过   0 是，1 否
                        qianpenZhiMa();
                    }else {
                        ToastUtil.getInstant().show(getApplicationContext(),"授权通过!");
                        GoSesameAuthorizedActivity.this.finish();
                    }
                }
                break;
            default:
                break;
        }
    }


    /**
     * 芝麻信用钱盆接口 2018.1.3
     */
    private void qianpenZhiMa() {
        UserLoginInfo userLoginInfo = DMApplication.getInstance().getmUserLoginInfo();
        String usid = userLoginInfo.getUserId();

        HttpParams params = new HttpParams();
        params.put("userId",usid);
        show();

        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.EXECUTE_CREDIT_ZHIMA, params, new RequestCallBack<CreditParamBean>() {
            @Override
            public void onSuccess(JsonResult<CreditParamBean> response) {

                if(DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    CreditParamBean creditParamBean = response.getObject();

                   /* Timer timer = new Timer();
                    timer.schedule(new TimerTask() {
                        public void run() {
                            dismiss();
                            GoSesameAuthorizedActivity.this.finish();
                        }
                    }, 1000, 5000);
*/
                    startCredit(creditParamBean);
                }else {
                    ToastUtil.getInstant().show(GoSesameAuthorizedActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(GoSesameAuthorizedActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {
                dismiss();
            }
        });

    }


    private CreditApp mCreditApp;
    private void startCredit(CreditParamBean creditParamBean) {
//        mCreditApp = CreditApp.getOrCreateInstance(GoSesameAuthorizedActivity.this);
////        HashMap<String, String> extParams = new HashMap<>();
////        String sign = creditParamBean.getSign();
////        String appId = creditParamBean.getAppId();
////        String params = creditParamBean.getParam();
////        show();
        String url = creditParamBean.getUrl();
        Bundle bundle = new Bundle();
//        bundle.putSerializable("isSesame", "1");
        bundle.putSerializable("url", url);
        bundle.putSerializable(ConstantAppInfo.AGREEMENT_ID, "100");
        startActivity(AgreementActivity.class, bundle);
        GoSesameAuthorizedActivity.this.finish();
//        mCreditApp.authenticate(GoSesameAuthorizedActivity.this, appId, null, params, sign, extParams, new ICreditListener() {
//
//            @Override
//            public void onComplete(Bundle bundle) {
//                dismiss();
//                if (null != bundle) {
//                    HttpParams params = new HttpParams();
//                    Set<String> keys = bundle.keySet();
//                    for (String key : keys) {
//                        params.put(key, bundle.get(key));
//                        DMLog.i("======", key + " = " + bundle.getString(key));
//                    }
//                    UserLoginInfo userLoginInfo = DMApplication.getInstance().getmUserLoginInfo();
//                    String usid = userLoginInfo.getUserId();
//                    params.put("userId",usid);
//                    params.put("authResult","success");
//                    DMOKHttpUtils.getInstance().post(GoSesameAuthorizedActivity.this, DMConstant.ApiURL.EXECUTE_CREDIT_ZHIMA_CALLBACK, params, new RequestCallBack<String>() {
//                        @Override
//                        public void onSuccess(JsonResult<String> response) {
//                            if (response.isReqDataSuccess()) {
//                                //芝麻授权成功回调
//
//                                Bundle bundle = new Bundle();
//                                bundle.putSerializable(ConstantAppInfo.BASIC_INFO_BEAN, basicInfoBean);
//                                if(isConfirml){                         //如果是从认证中心过来
//                                    GoSesameAuthorizedActivity.this.finish();
////                                    bundle.putString(ConstantAppInfo.PROJECT_TYPE, LoanType.JBD);     //需求更改注释掉代码 2018.2.8
////                                    startActivity(ConfirmInfoJinbaoActivity.class, bundle,true);
//                                }else {
//                                    bundle.putString(ConstantAppInfo.PROJECT_TYPE, LoanType.JBD);
//                                    startActivity(ConfirmInfoJinbaoActivity.class, bundle,true);
//
//
//                                    /**** 需求更改注释掉跳转工作证明的 2018.2.8
//                                    int isWorkProof = basicInfoBean.getIsWorkProof();
//                                    if(isWorkProof != 0){
//                                        startActivity(WorkProofActivity.class, bundle,true);
//                                        GoSesameAuthorizedActivity.this.finish();
//                                    }else {
//                                        GoSesameAuthorizedActivity.this.finish();
//                                    }
//                                    **************/
//
//                                }
//                            } else {
//                                ToastUtil.getInstant().show(GoSesameAuthorizedActivity.this, response.getDescription());
//                                GoSesameAuthorizedActivity.this.finish();
//                            }
//                        }
//
//                        @Override
//                        public void onFailure(String msg) {
//                            dismiss();
//                            ToastUtil.getInstant().show(GoSesameAuthorizedActivity.this, msg);
//                            GoSesameAuthorizedActivity.this.finish();
//                        }
//
//                        @Override
//                        public void onConnectFailure(String msg) {
//
//                        }
//                    });
//                }
//            }
//
//            @Override
//            public void onError(Bundle bundle) {
//                dismiss();
//                mCreditApp = null;
//                CreditApp.destroy();
//                ToastUtil.getInstant().show(GoSesameAuthorizedActivity.this, "授权失败");
//                GoSesameAuthorizedActivity.this.finish();
//            }
//
//            @Override
//            public void onCancel() {
//                dismiss();
//                mCreditApp = null;
//                CreditApp.destroy();
//                ToastUtil.getInstant().show(GoSesameAuthorizedActivity.this, "取消授权");
//                GoSesameAuthorizedActivity.this.finish();
//            }
//        });

    }


    /***
     * 同盾认证接口
     */
    private void withTheShieldCertification() {

        UserLoginInfo userLoginInfo = DMApplication.getInstance().getmUserLoginInfo();
        String usid = userLoginInfo.getUserId();

        HttpParams params = new HttpParams();
        params.put("userId",usid);
        show();

        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.EXECUTE_CREDIT_TONGDUN, params, new RequestCallBack<TongDunBean>() {
            @Override
            public void onSuccess(JsonResult<TongDunBean> response) {
                dismiss();
                if(DMConstant.Code.CODE_OK.equals(response.getCode())){
                    TongDunBean tongDunBean = response.getObject();
                    if(tongDunBean != null){
//                        String msg = tongDunBean.getMessage();
//                        ToastUtil.getInstant().show(getApplicationContext(), msg);

                        qianpenZhiMa();

                    }else {
                        ToastUtil.getInstant().show(getApplicationContext(), getString(R.string.failed_certified));
                    }
                }else{
                    ToastUtil.getInstant().show(getApplicationContext(), response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(getApplicationContext(), msg);
            }

            @Override
            public void onConnectFailure(String msg) {
                dismiss();
            }
        });
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        CreditApp.onActivityResult(requestCode, resultCode, data);
    }
}
